package com.pet.server.ext.action.timeline;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.Image;
import com.pet.server.ext.data.TimeLine;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.NumberUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;

public class Add extends ActionBase{

	public String text;
	public Integer pet_id;
	private List<String> images;
	public Add(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		images=new ArrayList<String>();
		text = params.getFieldValue("text");
		pet_id=NumberUtil.getInteger(params.getFieldValue("pet_id"), -1);
		int i=0;
		while(params.getFileUrl("image"+i)!=null){
			images.add(params.getFileUrl("image"+i));
			i++;
		}
		if(StringUtil.isEmpty(text)){
			throw ApiError.Type.INVALID_PARAM.toException();
		}
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();

		TimeLine line = new TimeLine();
		line.user_id=user.user_id;
		line.pet_id=pet_id;
		line.text=text;
		line.create_time=new Date();
		userService.saveTimeLine(line);
		List<Image> list=new ArrayList<Image>();
		for(String image:images){
			Image img = new Image();
			img.type=BaseAttribute.image_type.time_line.toString();
			img.src=image;
			img.oid=line.id;
			userService.saveImage(img);
			list.add(img);
		}
		line.list=list;
		Result result = new Result();
		result.put("data", BeanToJson.objectToJson(line, "oid","type"));
	    return result;
	}
}
